package com.bi.design.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bi.design.entity.SysUser;
import com.bi.design.mapper.SysUserMapper;
import com.bi.design.query.SysUserPageQuery;
import com.bi.design.service.SysUserService;
import com.bi.design.tools.PageInfo;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Objects;

@Service
@RequiredArgsConstructor
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {
    private final SysUserMapper sysUserMapper;


    @Override
    public PageInfo<SysUser> getPageQuery(SysUserPageQuery query) {
        return sysUserMapper.selectPage(new PageInfo<>(query.getPageCurr(), query.getPageSize()), Wrappers.lambdaQuery(SysUser.class)
                .eq(StringUtils.isNotBlank(query.getAccount()), SysUser::getAccount, query.getAccount())
                .like(StringUtils.isNotBlank(query.getNickName()), SysUser::getNickName, query.getNickName())
                .like(StringUtils.isNotBlank(query.getContactTel()), SysUser::getContactTel, query.getContactTel())
        );
    }


    @Override
    public Long addAndEdit(SysUser dto) {
        final PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        if (StringUtils.isNotBlank(dto.getPassword())) {
            dto.setPassword(passwordEncoder.encode(dto.getPassword()));
        }
        if (Objects.isNull(dto.getId())) {
            // 检查登陆账号是否存在
            SysUser sysUser = sysUserMapper.selectOne(Wrappers.lambdaQuery(SysUser.class)
                    .eq(SysUser::getAccount, dto.getAccount()));
            if (Objects.nonNull(sysUser)) {
                throw new RuntimeException("该账号已存在，请勿重复注册");
            }
            sysUserMapper.insert(dto);
        } else {
            // 账号不可更改
            dto.setAccount(null);
            sysUserMapper.updateById(dto);
        }
        return dto.getId();
    }

    @Override
    public void edit(SysUser user) {
        sysUserMapper.updateById(user);
    }

}
